package com.situ.springboot.controller;

import com.situ.springboot.util.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    //MultipartFile 封装了前端传递过来的图片信息
    @RequestMapping("/uploadImage")
    @ResponseBody
    public Result uploadImage(MultipartFile file) {
        //c1b7a34ba5044e7fbd952c04791d560e
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // abc.png
        String filename = file.getOriginalFilename();
        // png
        String extension = filename.substring(filename.lastIndexOf("."));
        //c1b7a34ba5044e7fbd952c04791d560e.png
        String newFilename = uuid + extension;
        String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Result.ok("上传成功", newFilename);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        //c1b7a34b-a504-4e7f-bd95-2c04791d560e
        System.out.println(uuid);
        //c1b7a34ba5044e7fbd952c04791d560e
        System.out.println(uuid.replace("-", ""));

        String filename = "abc.png";
        String extension = filename.substring(filename.lastIndexOf("."));
        System.out.println(extension);
    }
}
